package org.example.im.client.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.example.im.bean.protocol.request.HeartBeatRequestPacket;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author dingrui
 * @since 2022/2/12
 * @description 心跳
 */
@Component
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    private static final int HEART_BEAT_DURATION = 5_000;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.sendHeartBeatBySchedule(ctx);
        super.channelActive(ctx);
    }

    private void sendHeartBeatBySchedule(ChannelHandlerContext ctx) {
        ctx.executor().schedule(
                () -> {
                    if (ctx.channel().isActive()) {
                        ctx.writeAndFlush(new HeartBeatRequestPacket());
                        this.sendHeartBeatBySchedule(ctx);
                    }
                }
                , HEART_BEAT_DURATION, TimeUnit.MILLISECONDS);
    }
}
